<script setup>
import { reactive, onMounted, watch } from 'vue';
import axios from 'axios';


const ElMessage = {
  success: (message) => alert(`Success: ${message}`),
  error: (message) => alert(`Error: ${message}`),
  warning: (message) => alert(`Warning: ${message}`),
  info: (message) => alert(`Info: ${message}`),
};

const props = defineProps({
  courseId: {
    type: String,
    required: true,
  },
});

const formData = reactive({
  courseName: '',
  courseId: '',
  courseOutline: '', // This is the frontend property name
  teachingGoal: '',
  examinationMethod: '',
});

const fetchCourseDetails = async (currentCourseId) => {
  console.log('fetchCourseDetails: Function called with currentCourseId:', currentCourseId);

  if (!currentCourseId) {
    console.error('fetchCourseDetails: currentCourseId is empty, cannot fetch details.');
    ElMessage.error('无法加载课程详情：缺少课程ID。');
    resetForm();
    return;
  }
  try {
    const response = await axios.get(`/api/courses/${currentCourseId}`);
    const responseData = response.data; 

    console.log('fetchCourseDetails: API response received. Data:', responseData);

    if (responseData) {
      formData.courseId = responseData.courseId;
      formData.courseName = responseData.courseName;

      formData.courseOutline = responseData.course; 
      formData.teachingGoal = responseData.teachingGoal;
      formData.examinationMethod = responseData.examinationMethod;

      console.log('fetchCourseDetails: formData after update:', { ...formData });
    } else {
      console.warn(`fetchCourseDetails: No data found for ID ${currentCourseId} in response.data.`);
      ElMessage.warning(`未找到 ID 为 ${currentCourseId} 的课程信息。`);
      resetForm();
    }
  } catch (error) {
    console.error(`获取课程详情失败的详细错误 (在组件中捕获):`, error);
    if (error.response && error.response.status === 404) {
      ElMessage.error(`课程 ${currentCourseId} 不存在或已被删除。`);
    } else {
      ElMessage.error('加载课程详情失败，请重试。');
    }
    resetForm();
  }
};

const saveCourse = async () => {
  if (!formData.courseId || formData.courseId.trim() === '') {
    ElMessage.error('课程代码无效，无法保存。请刷新页面重试！');
    return;
  }
  if (!formData.courseName || formData.courseName.trim() === '') {
    ElMessage.error('课程名称不能为空！');
    return;
  }

  const payload = {
    courseId: formData.courseId,
    courseName: formData.courseName,

    course: formData.courseOutline, 
    teachingGoal: formData.teachingGoal,
    examinationMethod: formData.examinationMethod,
  };

  try {
    console.log('saveCourse: Sending PUT request with payload:', payload);
    await axios.put(`/api/courses/${formData.courseId}`, payload);
    ElMessage.success('课程更新成功！');

    fetchCourseDetails(formData.courseId);
  } catch (error) {
    console.error('保存课程失败的详细错误 (在组件中捕获):', error);
    if (error.response) {
      if (error.response.status === 400) {
        ElMessage.error('保存失败：请求数据无效。');
      } else if (error.response.status === 404) {
        ElMessage.error('保存失败：课程不存在。');
      } else {
        ElMessage.error('保存课程失败，请重试。');
      }
    } else {
      ElMessage.error('保存课程失败，请检查网络或后端服务。');
    }
  }
};

const resetForm = () => {
  formData.courseName = '';
  formData.courseOutline = ''; // Resetting the frontend property name
  formData.teachingGoal = '';
  formData.examinationMethod = '';
  ElMessage.info('表单已重置，课程ID保持不变。');
};

onMounted(() => {
  console.log('CourseMaintenanceForm: onMounted - props.courseId:', props.courseId);
  // Initial fetch is handled by the immediate watcher for props.courseId
});

watch(() => props.courseId, (newId, oldId) => {
  console.log('CourseMaintenanceForm: watch - props.courseId changed from', oldId, 'to', newId);
  if (newId && newId !== oldId) {
    fetchCourseDetails(newId);
  }
}, { immediate: true });
</script>

<template>
  <div class="course-maintenance-page container-fluid">
    <h1 class="h2 page-title">
      课程设置
    </h1>

    <div class="row justify-content-center">
      <div class="col-lg-8 col-md-10">
        <div class="card shadow-sm data-card">
          <div class="card-header d-flex align-items-center">
            <h5 class="mb-0">
              课程信息
            </h5>
          </div>
          <div class="card-body p-4">
            <form
              class="course-form"
              @submit.prevent="saveCourse"
            >
              <div class="row">
                <div class="col-md-6">
                  <div class="form-group mb-3">
                    <label
                      for="courseName"
                      class="form-label"
                    >课程名称：</label>
                    <input
                      id="courseName"
                      v-model="formData.courseName"
                      type="text"
                      class="form-control"
                      placeholder="请修改课程名称"
                    >
                  </div>
                </div>
                <div class="col-md-6">
                  <div class="form-group mb-3">
                    <label
                      for="courseId"
                      class="form-label"
                    >课程代码：</label>
                    <input
                      id="courseId"
                      v-model="formData.courseId"
                      type="text"
                      class="form-control"
                      placeholder="课程代码"
                      readonly
                    >
                  </div>
                </div>
              </div>

              <div class="form-group mb-3">
                <label
                  for="courseOutline"
                  class="form-label"
                >课程大纲：</label>
                <textarea
                  id="courseOutline"
                  v-model="formData.courseOutline"
                  class="form-control"
                  rows="4"
                  placeholder="请修改课程大纲"
                />
              </div>

              <div class="form-group mb-3">
                <label
                  for="teachingGoal"
                  class="form-label"
                >教学目标：</label>
                <textarea
                  id="teachingGoal"
                  v-model="formData.teachingGoal"
                  class="form-control"
                  rows="4"
                  placeholder="请修改教学目标"
                />
              </div>

              <div class="form-group mb-4">
                <label
                  for="examinationMethod"
                  class="form-label"
                >考核方式：</label>
                <textarea
                  id="examinationMethod"
                  v-model="formData.examinationMethod"
                  class="form-control"
                  rows="4"
                  placeholder="请修改考核方式"
                />
              </div>

              <div class="d-flex justify-content-end mt-4 pt-3 border-top">
                <button
                  type="submit"
                  class="btn btn-primary me-2"
                >
                  <i class="bi bi-check-lg me-1" /> 保存课程
                </button>
                <button
                  type="button"
                  class="btn btn-secondary"
                  @click="resetForm"
                >
                  <i class="bi bi-arrow-clockwise me-1" /> 重置
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import '../../assets/css/theme.css';

.course-maintenance-page {
  padding: 1.5rem;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.page-title {
  margin-bottom: 1.5rem;
}

.data-card {
  border: none;
  border-radius: 0.75rem;
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
  /* 移除 overflow: hidden 以避免按钮被裁剪 */
  background-color: #ffffff;
}

.card-header {
  border-bottom: none;
  padding: 1.25rem 1.5rem;
  background-color: var(--primary);
  color: white;
  font-size: 1.25rem;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.card-body {
  padding: 1.5rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-label {
  font-weight: 500;
  margin-bottom: 0.5rem;
}

.form-control {
  border-radius: 0.25rem;
  padding: 0.75rem 1rem;
  font-size: 1rem;
}

textarea.form-control {
  resize: vertical;
}

.btn {
  min-width: 120px;
  font-size: 0.95rem;
  padding: 0.65rem 1.2rem;
  border-radius: 0.375rem;
  transition: all 0.2s ease-in-out;
}

.btn-primary {
  background-color: var(--primary);
  border-color: var(--primary);
}

.btn-primary:hover {
  background-color: var(--primary-dark);
  border-color: var(--primary-dark);
}

.btn-secondary {
  background-color: var(--gray);
  border-color: var(--gray);
  color: white;
}

.btn-secondary:hover {
  background-color: var(--gray-dark);
  border-color: var(--gray-dark);
}

.d-flex.justify-content-end.mt-4.pt-3.border-top {
  border-color: var(--light) !important;
}

.btn i {
  margin-right: 0.5rem;
}
</style>
